﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;

namespace SEO.Spider
{
    /// <summary>
    /// 版权所有: 版权所有(C) 2011，Adin Lee
    /// 内容摘要: 百度长尾关键词抓取类
    /// 完成日期：2011年6月11日
    /// 版    本：V1.0 
    /// 作    者：Adin
    /// </summary>
    public class RelationKeywordsBaidu
    {
        SEO.Utility.IniFile iniFile = new Utility.IniFile(System.Windows.Forms.Application.StartupPath + "\\config.ini");

        /// <summary>
        /// 抓取百度搜索结果
        /// </summary>
        /// <param name="strWebUrl">网址</param>
        /// <param name="strStartMarkString">开始标记</param>
        /// <param name="strEndMarkString">结束标记</param>
        /// <param name="rb">显示实时消息控件</param>
        /// <param name="strSourceName">关键词</param>
        public void AccordingURLGetResultList(string strWebUrl, string strStartMarkString, string strEndMarkString, System.Windows.Forms.RichTextBox rb, string strKeywordsName)
        {
            try
            {
                SEO.Utility.WebClient wc = new SEO.Utility.WebClient();
                wc.Encoding = System.Text.Encoding.GetEncoding("utf-8");
                wc.OpenRead(strWebUrl);
                string GetHtmlCode = wc.RespHtml;

                //匹配列表源代码
                Regex rx = new Regex(strStartMarkString + "(?<content>[\\s\\S]*)?" + strEndMarkString, RegexOptions.Singleline);
                string strGetListHtmlContent = rx.Match(GetHtmlCode).Result("${content}");

                GetSearchResultsByLinks(strGetListHtmlContent, rb, strKeywordsName);
            }
            catch (Exception ex)
            {
                string strError = "百度搜索结果列表抓取匹配失败，关键词：" + strKeywordsName + "\r\n" + ex.Message;
                SEO.Utility.Log.SaveErrorLog("抓取百度搜索结果入口 -> " + strError);
            }

        }

        /// <summary>
        /// 分析关键词的长尾关键词
        /// </summary>
        /// <param name="strGetHtmlContent">匹配到的HTML代码</param>
        /// <param name="rb">显示实时消息控件</param>
        /// <param name="strKeywordsName">关键词</param>
        public void GetSearchResultsByLinks(string strGetHtmlContent, System.Windows.Forms.RichTextBox rb, string strKeywordsName)
        {
            try
            {
                strGetHtmlContent = strGetHtmlContent.Replace("</a>","|");
                strGetHtmlContent = SEO.Utility.StringHelper.CleanHtml(strGetHtmlContent);
                strGetHtmlContent = strGetHtmlContent.Replace("相关搜索","");
                strGetHtmlContent = strGetHtmlContent.Replace("\r", "");
                strGetHtmlContent = strGetHtmlContent.Replace("\n", "");
                strGetHtmlContent = strGetHtmlContent.Replace("\t", "");
                strGetHtmlContent = strGetHtmlContent.Substring(0, strGetHtmlContent.Length - 1);
                string[] splitContent = strGetHtmlContent.Split(new char[] { '|' });
                for (int i = 0; i < splitContent.Length; i++)
                {
                    string strKeywords = splitContent[i];

                    SEO.Utility.PublicValue.SaveMessage(Convert.ToDateTime(DateTime.Now).ToString("MM-dd HH:mm:ss") + " 正在分析 " + strKeywords + " ...");
                    rb.Text = SEO.Utility.PublicValue.GetMessage();

                    string strStatus = "";
                    try
                    {
                        SEO.DAL.RelationKeywordsDAL rsdal = new DAL.RelationKeywordsDAL();
                        if (rsdal.CheckKeywordsDayRankIsExist(strKeywords))
                        {
                            strStatus = "关键词重复！";
                        }
                        else if (string.IsNullOrEmpty(strKeywords))
                        {
                            strStatus = "关键词为空！";
                        }
                        else
                        {
                            //判断是否勾选了长尾词必须包含关键词
                            string strContain = iniFile.GetString("OPTION", "contain", "");
                            if (strContain == "1")
                            {
                                if (strKeywords.Contains(strKeywordsName.Trim()))
                                {
                                    SEO.Model.RelationKeywords rs = new Model.RelationKeywords();
                                    rs.KeyID = rsdal.GetAutoAddNum();
                                    rs.KeyName = strKeywords;
                                    rs.IsCatch = 0;
                                    SEO.BLL.RelationKeywordsBLL rsbll = new BLL.RelationKeywordsBLL();
                                    rsbll.InsertRelationKeywordsBLL(rs);
                                }
                            }
                            else
                            {
                                SEO.Model.RelationKeywords rs = new Model.RelationKeywords();
                                rs.KeyID = rsdal.GetAutoAddNum();
                                rs.KeyName = strKeywords;
                                rs.IsCatch = 0;
                                SEO.BLL.RelationKeywordsBLL rsbll = new BLL.RelationKeywordsBLL();
                                rsbll.InsertRelationKeywordsBLL(rs);
                            }

                            strStatus = "成功加入！";
                        }
                    }
                    catch (Exception ex)
                    {
                        strStatus = "加入失败！";
                        SEO.Utility.Log.SaveErrorLog("添加RelationKeywords数据到本地Sqlite数据库 -> " + ex.Message);
                    }

                    SEO.Utility.PublicValue.SaveMessage("\r\n" + Convert.ToDateTime(DateTime.Now).ToString("mm:ss") + " 状态：" + strStatus);
                    rb.Text = SEO.Utility.PublicValue.GetMessage();
                }
            }
            catch (Exception ex)
            {
                SEO.Utility.Log.SaveErrorLog("获取网页地址列表 ->" + ex.Message);
            }
        }


    }
}
